//
//  DispatchBillViewController.swift
//  ZNHXManagement
//
//  Created by 四川中农 on 2018/9/28.
//  Copyright © 2018年 四川中农. All rights reserved.
//

import UIKit
import HandyJSON
import DZNEmptyDataSet

class DispatchBillViewController: BaseViewController {

    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var navHeight: NSLayoutConstraint!
    @IBOutlet weak var headerView: UIView!
    @IBOutlet weak var allBtn: UIButton!
    @IBOutlet weak var orderNum: UILabel!
    @IBOutlet weak var todayDate: UILabel!
    @IBOutlet weak var addressBtn: UIButton!
    @IBOutlet weak var historybutton: UIButton!
    @IBOutlet weak var backButton: UIButton!
    var model:DispatchBillModel!
    
    var viewLine:UIView!
    
    var lastSeleBtn:UIButton!
    
    var isHistory = false
    
    var id = 0 //  id为0返回今日发货单数据
    
    var type = 0 // 0所有 1待处理 2已处理
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.navHeight.constant = Utils.isIphoneX() ? 88 : 64
        self.initViewLine()
        self.tableView.rowHeight = 60
        
        if self.isHistory {
            self.titleLabel.text = "历史发货单"
            self.backButton.isHidden = false
            self.historybutton.isHidden = true
        }else{
            self.todayDate.text = Date().passDate().dateNowAsString("YYYY-MM-dd")
        }
        
        PKhud.show()
        getOrderInvoiceDetail()
        self.tableView.tableFooterView = UIView()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: true)
    }
    
    @IBAction func backButtonMethod(_ sender: UIButton) {
        self.backBarButtonMethon()
    }
    // MARK:所有
    @IBAction func allBtnClick(_ sender: UIButton) {
        checkSeleBtn(sender: sender)
    }
    
    // MARK:待处理
    @IBAction func pendingClick(_ sender: UIButton) {
        checkSeleBtn(sender: sender)
    }
    
    // MARK: 已处理
    @IBAction func pendedClick(_ sender: UIButton) {
        checkSeleBtn(sender: sender)
    }
    
    func checkSeleBtn(sender:UIButton) {
        guard self.lastSeleBtn != sender else{
            return
        }
        self.type = sender.tag - 100
        let width = UIScreen.ScreenWidth / 3
        UIView.animate(withDuration: 0.2) {
            self.viewLine.left = width * CGFloat(self.type + 1) - (width/2) - 38/2
        }
        
        sender.titleLabel?.font = UIFont.boldSystemFont(ofSize: 13)
        self.lastSeleBtn.titleLabel?.font = UIFont.systemFont(ofSize: 13)
        sender.isSelected = true
        self.lastSeleBtn.isSelected = false
        self.lastSeleBtn = sender
        
        getOrderInvoiceDetail()
        
    }
    
    // MARK:历史发货单
    @IBAction func rightBarButtonMethod(_ sender: UIButton) {
        let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "HistoryDispatchBillViewController") as! HistoryDispatchBillViewController
        ctrl.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(ctrl, animated: true)
    }
    
    func initViewLine(){
        self.lastSeleBtn = self.allBtn
        self.viewLine = UIView.init(frame: CGRect.init(x: UIScreen.ScreenWidth / 3 / 2 - (38 / 2), y: self.headerView.height - 1.5, width: 38, height: 1.5))
        self.viewLine.backgroundColor = UIColor.init(hexColor: "#f7c201")
        self.headerView.addSubview(self.viewLine)
    }

}

extension DispatchBillViewController:UITableViewDelegate,UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.model != nil ? self.model.orders.count : 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "DispatchBillTableViewCell") as! DispatchBillTableViewCell
        cell.model = self.model.orders[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "OrderDetailViewController") as! OrderDetailViewController
        ctrl.hidesBottomBarWhenPushed = true
        ctrl.id = self.model.orders[indexPath.row].id
        self.navigationController?.pushViewController(ctrl, animated: true)
    }
    
}

extension DispatchBillViewController:DZNEmptyDataSetSource,DZNEmptyDataSetDelegate{
    func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
        let str = "空空如也~"
        let attribute = NSMutableAttributedString.init(string: str)
        attribute.addAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 14),
                                 NSAttributedStringKey.foregroundColor:UIColor.init(hexColor: "666666")], range: NSRange.init(location: 0, length: str.count))
        
        return attribute
    }
    
    func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! {
        return UIImage.init(named: "img_Defaultheadimage")
    }
}

extension DispatchBillViewController{
    
    func getOrderInvoiceDetail(){
        
        let parameter:postParameters = ["id":self.id,"type":self.type]
        HttpRequest.requestData(.post, URLString: Api.orderInvoiceDetail.rawValue, parameters: parameter) { (result) in
            PKhud.hiden()
            if result["msg"] as! String == "success"{
                if let jsonDic = result["data"] as? postParameters{
                    let model = JSONDeserializer<DispatchBillModel>.deserializeFrom(dict: jsonDic)
                    self.model = model
                    self.orderNum.text = self.model.number
                    self.addressBtn.setTitle(Utils.getUserDefaulsFor(key: "address") as? String, for: .normal)
                    self.tableView.reloadData()
                }
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
}

















